package indi.wshape1.takeawaydeliveryinfo.interceptor;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import indi.wshape1.takeawaydeliveryinfo.pojo.Sender;
import indi.wshape1.takeawaydeliveryinfo.service.AdminService;
import indi.wshape1.takeawaydeliveryinfo.service.RootService;
import indi.wshape1.takeawaydeliveryinfo.service.SenderService;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Wshape1
 * @version 1.0
 * @description 登录拦截器，对未登录用户转发至登陆页面  拦截路径 / /page /more /change
 * @since 2023-01-17
 */

public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String path = request.getServletPath();
        boolean turnToLogin = true;
//        session.phone 为空表示没有登录
        if (request.getSession().getAttribute("phone") == null) {

            // 查询cookie实现免登录
            if (request.getCookies() != null)
                for (Cookie cookie : request.getCookies()) {
//                若找到noLogin Cookie 则进行密码验证 成功就进入 失败就返回登录页面
                    if ("noLogin".equals(cookie.getName())) {
                        if (verifyPassword(cookie.getValue())) {
                            //  type:phone:password
                            String[] strings = cookie.getValue().split(":");
                            request.getSession().setAttribute("phone", strings[1]);
                            request.getServletContext().setAttribute(strings[1], strings[0]);
                            turnToLogin = false;
                        }
                    }
                }
        } else {

            // Session.phone 存在 而 server.application.{phone} 不存在 则
            String phone = (String) request.getSession().getAttribute("phone");
            if (request.getServletContext().getAttribute(phone) == null) {
                String type = "root";
                if (phone.matches("-?[0-9]+.?[0-9]*")) {

                    QueryWrapper<Sender> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("phone", phone);
                    Sender one = senderService.getOne(queryWrapper);

                    if (one != null) {
                        type = "sender";
                    } else {
                        type = "admin";
                    }

                }

                request.getServletContext().setAttribute(phone, type);
            }

            turnToLogin = false;
        }

        //用户未登录 需要登录
        if (turnToLogin) {
            if (!"/".equals(path)) {
                response.sendRedirect("/");
                return false;
            }
        } else {        // 反之用户已登录
            if ("/".equals(path)) {
                response.sendRedirect("/page");
                return false;
            }
        }

        return true;
    }

    private SenderService senderService;
    private AdminService adminService;
    private RootService rootService;

    public LoginInterceptor() {
    }

    public LoginInterceptor(SenderService senderService, AdminService adminService, RootService rootService) {
        this.senderService = senderService;
        this.adminService = adminService;
        this.rootService = rootService;
    }

    /**
     * 验证密码
     *
     * @param str type:phone:password
     * @return true or false
     */
    private boolean verifyPassword(String str) {
        String[] strings = str.split(":");
        String type = strings[0];
        String phone = strings[1];
        String password = strings[2];

        switch (type) {
            case "sender":
                return senderService.verify(phone, password);
            case "admin":
                return adminService.verify(phone, password);
            case "root":
                return rootService.verify(phone, password);
            default:
                return false;
        }
    }


}
